const _ = require('lodash');
const config = require('../config');
const JsonIO = require('./utils/jsonio');
const parseAdoc = require('./utils/adoc-parser');
const Renderer = require('./utils/renderer');
const through2 = require('through2');

const adocInfoIO = new JsonIO(config.dbPath);
const adocRenderer = new Renderer(`${config.templateDir}/article.hbs`);

const adocName = (path) => path.substring(config.blogDir.length + 1, path.length - 5);

const saveAdocInfoToFile = (info) => {
  console.log('adoc info saved')
  const data = adocInfoIO.read() || {};
  data[info.adocName] = info;
  adocInfoIO.write(data);
};

module.exports = () => {
  return through2.obj(function(file, encoding, cb) {
    if (file.isBuffer()) {
      const { adocInfo, content } = parseAdoc(file.contents.toString());
      console.log('-> adoc building: ' + adocInfo.title);

      adocInfo.adocName = adocName(file.history[0]);
      saveAdocInfoToFile(adocInfo);

      const html = adocRenderer.render({
        content,
        title: adocInfo.title,
        author: adocInfo.author,
        version: adocInfo.version,
        date: adocInfo.date,
        tags: adocInfo.tags,
        nav: config.site.nav,
        logo: config.site.logo,
        analysis: config.site.analysis
      });

      file.contents = Buffer.from(html);
    }
    cb(null, file);
  });
};
